import 'dart:async';
import 'dart:io';
import 'dart:math';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:orginone/components/CommandWidget/index.dart';
import 'package:orginone/components/EmptyWidget/EmptyWidget.dart';
import 'package:orginone/components/XImage/XImage.dart';
import 'package:orginone/components/ListWidget/ListWidget.dart';
import 'package:orginone/components/TabContainerWidget/types.dart';
import 'package:orginone/components/XLazy/XLazy.dart';
import 'package:orginone/components/XStatefulWidget/XStatefulWidget.dart';
import 'package:orginone/components/FileWidget/FileListWidget/components/FileTaskListWidget/FileTaskListWidget.dart';
import 'package:orginone/config/constant.dart';
import 'package:orginone/dart/base/model.dart';
import 'package:orginone/dart/base/schema.dart';
import 'package:orginone/dart/core/chat/session.dart';
import 'package:orginone/dart/core/public/entity.dart';
import 'package:orginone/dart/core/target/innerTeam/department.dart';
import 'package:orginone/dart/core/target/outTeam/cohort.dart';
import 'package:orginone/dart/core/target/outTeam/group.dart';
import 'package:orginone/dart/core/target/person.dart';
import 'package:orginone/dart/core/target/team/company.dart';
import 'package:orginone/dart/core/thing/directory.dart';
import 'package:orginone/dart/core/thing/standard/property.dart';
import 'package:orginone/dart/core/thing/systemfile.dart';
import 'package:orginone/routers/pages.dart';
import 'package:orginone/utils/file_utils.dart';
import 'package:orginone/utils/log/log_util.dart';

import '../../../dart/base/common/commands.dart';
import '../../../routers/app_route.dart';
import '../../ProgressBarWidget/ProgressBarWidget.dart';
import '../../TabContainerWidget/TabContainerWidget.dart';
import '../../XButtonBar/XButtonBar.dart';
import '../../XConsumer/XConsumer.dart';

/// 文件列表页面
class FileListWidget extends XStatefulWidget {
  FileListWidget({super.key, super.data});
  @override
  State<StatefulWidget> createState() => _FileListState();
}

class _FileListState extends XStatefulState<FileListWidget, dynamic>
    with EmptyMixin {
  double progressUploud = 0.0;
  List<IEntity> directorys = <IEntity>[];
  List<TaskModel> listTask = <TaskModel>[];
  dynamic currentDic;
  bool isCalculate = false;
  String uploudKey = "";
  String emitKey = "emitKey";

  @override
  Widget buildWidget(BuildContext context, dynamic data) {
    // Widget content = Obx(() => directorys.isNotEmpty
    //     ? Container(
    //         margin: EdgeInsets.symmetric(vertical: 1.h),
    //         decoration: const BoxDecoration(color: Colors.white),
    //         child: Obx(() => _buildList(context, directorys.value)))
    //     : const EmptyFile());

    return addBottomBtnWidget(
        child: Column(
          children: [Expanded(child: _buildContent(context)), buildProgress()],
        ),
        context: context);
  }

  bool _hasTab(BuildContext context) {
    final tabCW = context.findAncestorWidgetOfExactType<TabContainerWidget>();
    return null != tabCW ?? false;
  }

  Widget _buildContent(BuildContext context) {
    return _hasTab(context)
        ? _buildLazyFileList(context, RoutePages.routeData)
        : XConsumer<AppRoute>(builder: (context, rd, child) {
            return _buildLazyFileList(context, rd);
          });
  }

  Widget _buildLazyFileList(BuildContext context, AppRoute rd) {
    return XLazy<IEntity<dynamic>>(
        initDatas: directorys,
        onInitLoad: () async {
          directorys = await getCurrentDirectory(rd.currPageData.data);
          return directorys;
        },
        builder: (context, args) {
          return Container(
              margin: EdgeInsets.symmetric(vertical: 1.h),
              decoration: const BoxDecoration(color: Colors.white),
              child: _buildList(context));
        });
  }

  FutureOr<List<IEntity>> getCurrentDirectory(dynamic data) async {
    List<IEntity> directorys = [];
    if (data is IPerson) {
      currentDic = data.directory;
      directorys = await loadAll<IDirectory>(data.directory);
    } else if (data is ICompany) {
      currentDic = data.directory;
      directorys = await loadAll<IDirectory>(data.directory);
    } else if (data is IDepartment) {
      currentDic = data.directory;
      directorys = await loadAll<IDirectory>(data.directory);
    } else if (data is ICohort) {
      currentDic = data.directory;
      directorys = await loadAll<IDirectory>(data.directory);
    } else if (data is IGroup) {
      currentDic = data.directory;
      directorys = await loadAll<IDirectory>(data.directory);
    } else if (data is IDirectory) {
      currentDic = data;
      directorys = await loadAll<IDirectory>(data);
    } else if (data is ISession) {
      currentDic = data.target.directory;
      directorys = await loadAll<IDirectory>(currentDic);
    }
    return directorys;
  }

  buildProgress() {
    return CommandWidget(
        type: 'file',
        cmd: 'uploading',
        builder: (context, args) {
          return progressUploud > 0
              ? ProgressBarWidget(progress: progressUploud)
              : Container();
        });
  }

  FutureOr<List<IEntity>> loadAll<T extends IDirectory>(T targtet) async {
    List<IEntity> directorys = [];
    directorys.addAll(await loadDirectorys<T>(targtet));
    directorys.addAll(await loadFiels<T>(targtet));
    directorys.addAll(await loadPropertys<T>(targtet));
    directorys = _filterDeleteed(directorys);

    return directorys;
  }

  ///过滤已删除的目录
  List<IEntity> _filterDeleteed(List<IEntity> directorys) {
    return directorys
        .where((element) => !element.groupTags.contains("已删除"))
        .toList();
  }

  FutureOr<List<IDirectory>> loadDirectorys<T extends IDirectory>(
      T target) async {
    List<IDirectory> directorysTemp = target.children;
    XLogUtil.d('>>>>>>======directorys ${directorysTemp.length}');

    if (directorysTemp.isEmpty) {
      var res = await target.loadContent(reload: target.children.isEmpty);
      if (res && target.children.isNotEmpty) {
        directorys = await getCurrentDirectory(data);
        directorysTemp = target.children;
      }
    }
    return directorysTemp;
  }

  ///加载文件
  FutureOr<List<ISysFileInfo>> loadFiels<T extends IDirectory>(T target) async {
    List<ISysFileInfo> files = target.files;
    XLogUtil.d('>>>>>>======files ${files.length}');
    if (files.isEmpty) {
      var res = await target.loadContent();
      if (res && target.files.isNotEmpty) {
        directorys = await getCurrentDirectory(data);
      }
    }
    return files;
  }

  ///加载属性
  FutureOr<List<IProperty>> loadPropertys<T extends IDirectory>(
      T target) async {
    List<IProperty> propertys = target.standard.propertys;
    if (propertys.isEmpty) {
      var res = await target.standard.loadPropertys();
      if (res.isNotEmpty) {
        directorys = await getCurrentDirectory(data);
      }
    }
    return propertys;
  }

  Widget addBottomBtnWidget(
      {required Widget child, required BuildContext context}) {
    return XButtonBar(
      body: child,
      listAction: [
        ActionModel(
            title: "新建",
            onTap: () async {
              showCreateDirectoryDialog(
                context,
                onCreate: (name, code, remark) async {
                  IDirectory iDirectory = currentDic;
                  XDirectory xx = XDirectory(
                      directoryId: iDirectory.directoryId,
                      id: '',
                      isDeleted: false);
                  xx.name = name;
                  xx.code = code;
                  xx.remark = remark;
                  await iDirectory.create(xx);
                },
              );
            }),
        ActionModel(
            title: "上传",
            onTap: () async {
              FilePickerResult? result = await FilePicker.platform
                  .pickFiles(type: FileType.any, allowMultiple: true);
              if (result != null) {
                RoutePages.jumpUploadFiles(filePicker: result);
                uploudKey = Random().nextDouble().toString();
                progressUploud = 0.01;
                command.emitter('file', 'uploading', progressUploud);

                for (var file in result.files) {
                  await currentDic?.createFile(File(file.path!), p: (progress) {
                    progressUploud = progress;
                    if (isCalculate) return;
                    progressUploud = getProgressTotal(result.files);
                    command.emitter('file', 'uploading', progressUploud);
                    if (progressUploud >= 1) {
                      command.emitter('executor', 'refresh', progressUploud);
                    }
                  }, tempKey: uploudKey);
                  directorys = await getCurrentDirectory(data);
                }
                if (progressUploud >= 1) {
                  progressUploud = 0.0;
                  command.emitter('file', 'uploading', progressUploud);
                }
                directorys = await getCurrentDirectory(data);
              }
            }),
        ActionModel(
            title: "上传列表",
            onTap: () {
              Future.delayed(const Duration(milliseconds: 500), () {
                showUploudList(context);
              });
            }),
      ],
    );
  }

  double getProgressTotal(List<PlatformFile> files) {
    isCalculate = true;
    listTask = currentDic.taskList;
    int percentageSize = 0;
    int totalSize = 0;

    for (var fileItem in files) {
      for (var taskItem in listTask) {
        String fileName = fileItem.path!.split("/").last;
        if (taskItem.name == fileName && taskItem.tempKey == uploudKey) {
          percentageSize = percentageSize +
              ((taskItem.finished / 100 * fileItem.size).toInt());
          break;
        }
      }
      totalSize = totalSize + fileItem.size;
    }
    isCalculate = false;
    return percentageSize / totalSize;
  }

  showUploudList(BuildContext context) {
    // listTask.value = currentDic.taskList;
    showDialog(
      context: context,
      builder: (context) => FileTaskListWidget(iDirectory: currentDic),
      useSafeArea: true,
    );
  }

  _buildList(BuildContext context) {
    var inited = false;
    return CommandWidget(
        type: 'executor',
        cmd: 'refresh',
        builder: (context, args) {
          if (null != args) {
            directorys.clear();
          } else if (inited && directorys.isNotEmpty) {
            directorys = _filterDeleteed(directorys);
          } else {
            inited = true;
          }
          return ListWidget(
            initDatas: directorys,
            onInitLoad: () async {
              directorys.addAll(await getCurrentDirectory(data));
              return directorys;
            },
            // getDatas: ([dynamic parentData]) {
            //   if (null == parentData) {
            //     return directorys;
            //   }
            //   LogUtil.d('>>>>>>======${parentData.runtimeType}');
            //   return [];
            // },
            getAction: (dynamic dataitem) {
              return GestureDetector(
                  onTap: () {
                    fileOperationModal(context, fileItem: dataitem, data: data);
                  },
                  child: XImage.localImage(XImage.moreAction));
            },
            // (dynamic data) {
            //   return GestureDetector(
            //       onTap: () {
            //         LogUtil.d('>>>>>>======点击了感叹号');
            //         // RoutePages.jumpEneityInfo(data: data);
            //       },
            //       child: const IconWidget(
            //         color: XColors.chatHintColors,
            //         iconData: Icons.info_outlined,
            //       ));
            // },
            onTap: (dynamic item, List children) {
              XLogUtil.d(
                  '>>>>>>======点击了列表项 ${item.name} ${item.id} ${children.length}');
              if (item is IDirectory) {
                // RoutePages.back(context);
                RoutePages.jumpFileList(context: context, data: item);
              } else if (item is SysFileInfo) {
                var extension = item.shareInfo().extension?.toLowerCase() ?? "";

                if (FileUtils.isImage(extension)) {
                  //图片左右滑动加载
                  var initIndex = 0;
                  List<String> listRes = [];
                  List listFile = directorys.whereType<SysFileInfo>().toList();
                  for (var element in listFile) {
                    var extension =
                        element.shareInfo().extension?.toLowerCase() ?? "";
                    if (FileUtils.isImage(extension)) {
                      listRes.add(getFilePath(element));
                    }
                  }
                  initIndex = listRes.indexOf(getFilePath(item));
                  RoutePages.jumpImagePageview(context, listRes, initIndex);
                } else {
                  RoutePages.jumpFile(context: context, file: item.shareInfo());
                }
              } else {
                RoutePages.jumpRelationInfo(data: item);
              }
            },
          );
        });
  }

  getFilePath(dynamic item) {
    return item.shareInfo().shareLink != null &&
            item.shareInfo().shareLink!.contains('http')
        ? item.shareInfo().shareLink!
        : '${Constant.host}${item.shareInfo().shareLink}';
  }
}
